package com.zjq.security.security.service;

import com.zjq.security.mapper.UserMapper;
import com.zjq.security.pojo.User;
import com.zjq.security.security.BaseUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;

/**
 * @User zhangjiaqi
 * @Project security
 * @Package com.zjq.security.security.service
 * @Date 2022/3/28 20:55
 * 当前类的作用,根据用户查询用户数据
 */
@Component
public class MyUserSetailService implements UserDetailsService {

    private UserMapper userMapper;

    @Autowired
    public void setUserMapper(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    /**
     * 当我们登录的时候传递过来的用户名
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException{
        User user = userMapper.findByUsername(username);
        //如果用户不存在
        if (user == null) {
            throw new UsernameNotFoundException("用户名密码不存在");
        }
        if (user.getStatus() == 0) {
            throw new AccountExpiredException("账号过期");
        }
        if (user.getStatus() == 2) {
            throw new LockedException("账号被封禁");
        }
        //参数1 用户名,就是当前用户名
        //参数2,数据库中查询到的密码
        //参数3 用户有的权限,可以后面再查询一样,可以在之类先查询,设置进去,也可以后面更新.,但是我们个人建议先写个空的
        //因为可能账号密码不对,你要获取权限需要查询数据库,就白查询了
        // return new org.springframework.security.core.userdetails.User(username, user.getPassword(), new ArrayList<>());
        //如果一个类本身的功能不足以满足我们的需求的时候,可以通过继承来扩展
        return new BaseUser(username, user.getPassword(), new ArrayList<>(), user.getUserId());
    }

}
